/*
 * @Author: yangrd
 * @Date: 2021-04-21 10:59:33
 * @LastEditTime: 2021-05-25 10:49:30
 * @Description: 工具库
 * @FilePath: \file-chunk\lib\utils.ts
 * 功能描述
 */
import SparkMD5 from 'spark-md5';
/**
 * @description: 
 * @param {*} len // 长度
 * @param {*} radix // 基数
 * @return {*} UUID
 */
export function uuid(len: number, radix: number): string {
    const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    const uuid = [];
    let i;
    radix = radix || chars.length;

    if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        // rfc4122, version 4 form
        let r;

        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';

        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
}


export function renderSize(value: any) {
    if (null == value || value == '') {
        return "0 B";
    }
    const unitArr: string[] = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
    let index = 0;
    const srcsize: number = parseFloat(value);
    index = Math.floor(Math.log(srcsize) / Math.log(1024));
    let size: any = srcsize / Math.pow(1024, index);
    size = size.toFixed(2); //保留的小数位数
    return size + unitArr[index];
}


export function dateFormat(fmt: string, date: Date | number) {
    interface dateType {
        "Y+": string, "m+": string, "d+": string, "H+": string, "M+": string, "S+": string
    }
    let ret
    date = new Date(date)
    const opt: dateType = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "M+": date.getMinutes().toString(), // 分
        "S+": date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    }
    for (const k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt)
        if (ret) {
            fmt = fmt.replace(
                ret[1],
                ret[1].length == 1 ? opt[k as keyof dateType] : opt[k as keyof dateType].padStart(ret[1].length, "0")
            )
        }
    }
    return fmt
}



export function Percentage(num: number, total: number): number {
    if (num == 0 || total == 0) {
        return 0;
    }
    return (Math.round(num / total * 10000) / 100.00);// 小数点后两位百分比
}

export class readFileHash {
    aborted: boolean;
    progress: number;
    constructor() {
        this.aborted = false;
        this.progress = 0;
    }
    md5(file: File, md5Fn: any, progressFn: any) {
        let currentChunk = 0;
        const blobSlice = File.prototype.slice
        const chunkSize = 2097152;
        const chunks = Math.ceil(file.size / chunkSize);
        const spark = new SparkMD5.ArrayBuffer();
        const reader = new FileReader();
        loadNext();
        reader.onloadend = e => {
            spark.append(e.target.result as ArrayBuffer); // Append array buffer
            currentChunk++;
            this.progress = currentChunk / chunks;

            if (progressFn && typeof progressFn === 'function') {
                progressFn(this.progress);
            }

            if (this.aborted) {
                md5Fn('aborted');
                return
            }

            if (currentChunk < chunks) {
                loadNext();
            } else {
                md5Fn(null, spark.end());
            }
        };

        function loadNext() {
            const start = currentChunk * chunkSize;
            const end = start + chunkSize >= file.size ? file.size : start + chunkSize;
            reader.readAsArrayBuffer(blobSlice.call(file, start, end));
        }
    }

    abort() {
        this.aborted = true;
    }
}